import os
from utils.tools import logger
from app.funcs import create_knowledge_base, split_txt,process_text

from app.client.MinioClient import MinioClient
from fastapi import APIRouter, File, UploadFile
from utils.response_util import response_200, response_403


uploadController = APIRouter()


@uploadController.post(
    "/books",
    summary="提交处理好的txt文件",
)
async def upload_file_api(file: UploadFile = File(...)):
    bucket = "books"
    filename = file.filename
    if not filename.endswith(".txt"):
        return response_403(data=False, message="文件格式错误，请上传txt文件")
    file_data = await file.read()
    file_size = len(file_data)
    minio_client = MinioClient()
    flag = minio_client.upload_obj(
        bucket=bucket,
        object_name=filename,
        file_data=file_data,
        file_size=file_size,
    )
    logger.info(f"上传文件{filename}成功，返回结果{flag}")

    # 拆分文本推送到队列
    split_txt.push(filename)
    # 使用chatat生成qa
    process_text.push(filename)

    # 创建知识库初始化robot
    create_knowledge_base.push(filename)

    return response_200(data=flag, message="上传成功")
